const express = require('express');
const router = express.Router();

// 获取所有容器
router.get('/', async (req, res) => {
  try {
    const containers = await req.docker.listContainers({ all: true });
    res.json(containers);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 获取容器详情
router.get('/:id', async (req, res) => {
  try {
    const container = req.docker.getContainer(req.params.id);
    const info = await container.inspect();
    res.json(info);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 启动容器
router.post('/:id/start', async (req, res) => {
  try {
    const container = req.docker.getContainer(req.params.id);
    await container.start();
    res.json({ message: '容器已启动' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 停止容器
router.post('/:id/stop', async (req, res) => {
  try {
    const container = req.docker.getContainer(req.params.id);
    await container.stop();
    res.json({ message: '容器已停止' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 删除容器
router.delete('/:id', async (req, res) => {
  try {
    const container = req.docker.getContainer(req.params.id);
    await container.remove({ force: true });
    res.json({ message: '容器已删除' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 获取容器日志
router.get('/:id/logs', async (req, res) => {
  try {
    const container = req.docker.getContainer(req.params.id);
    const logs = await container.logs({
      stdout: true,
      stderr: true,
      tail: 100,
      timestamps: true
    });
    res.send(logs.toString());
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 获取容器统计信息
router.get('/:id/stats', async (req, res) => {
  try {
    const container = req.docker.getContainer(req.params.id);
    const stats = await container.stats({ stream: false });
    res.json(stats);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

module.exports = router;
